package com.banciyuan.bcywebview.biz.web;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.biz.share.ShareActivity;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;

import java.net.URISyntaxException;
import java.util.HashMap;

/**
 * Created by hy on 2016/1/19.
 */
public class WebActivity extends BaseActivity implements ActionbarHelper.OnActionCallbacks {
    private String url;
    private WebView mWebView;
    private WebSettings mWebViewSettings;
    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private ProgressBar webviewProgressbar;
    private String imageUrl;
    private String title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        initArgs();
        initActionbar();
        initUi();
    }

    @Override
    protected void initArgs() {
        Intent intent = getIntent();
        url = intent.getStringExtra(gotoUtil.INTENT_VALUE_ONE);
        imageUrl = intent.getStringExtra(gotoUtil.INTENT_VALUE_TWO);
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setActionCallbacks(this);
        mActionbarHelper.addOneAction(R.drawable.share_black);
    }

    @Override
    protected void initUi() {
        webviewProgressbar = (ProgressBar) findViewById(R.id.webview_progressbar);
        mWebView = (WebView) findViewById(R.id.webview);
        mWebViewSettings = mWebView.getSettings();

        mWebViewSettings.setUseWideViewPort(true);
        mWebViewSettings.setDatabaseEnabled(true);
        mWebViewSettings.setDomStorageEnabled(true);
        mWebViewSettings.setJavaScriptEnabled(true);
        //mWebView.setWebContentsDebuggingEnabled(true);
        //set broswer ua
        mWebViewSettings.setUserAgentString(mWebViewSettings.getUserAgentString() + "Android-bcy/" + getVersion());
        mWebViewSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        WebChromeClient webChromeClient = new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                WebActivity.this.title = title;
                mActionbarHelper.setTitle(title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (webviewProgressbar != null) {
                    webviewProgressbar.setProgress(newProgress);
                    if (newProgress == 100) {
                        webviewProgressbar.setVisibility(View.GONE);
                    } else {
                        webviewProgressbar.setVisibility(View.VISIBLE);
                    }
                }
            }
        };
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("intent://")) {
                    try {
                        Intent intent = new Intent().parseUri(url, Intent.URI_INTENT_SCHEME);
                        if (intent != null) {
                            view.stopLoading();
                            PackageManager packageManager = getPackageManager();
                            ResolveInfo info = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
                            if (info != null) {
                                startActivity(intent);
                            } else {
                                String fallbackUrl = intent.getStringExtra("browser_fallback_url");
                                view.loadUrl(fallbackUrl);
                            }
                            return true;
                        }
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    } finally {
                        return false;
                    }
                } else {
                    return false;
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (webviewProgressbar.isShown())
                    webviewProgressbar.setVisibility(View.GONE);
                mActionbarHelper.setTitle(view.getTitle());
            }
        });

        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(final String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                if (url.endsWith(".apk") || StringUtil.notNullEqual(mimetype, "application/vnd.android.package-archive")) {
                    downLoadApk();
                }
            }
        });
        mWebView.setWebChromeClient(webChromeClient);
        mWebView.loadUrl(url);
    }

    private void downLoadApk() {
        try {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        if (null != mWebView && mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onBackClick() {
        finish();
    }

    @Override
    public void onActionClick(int id) {
        switch (id) {
            case R.id.base_action_bar_itemone:
                goShare();
                break;
        }
    }

    private void goShare() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("content", String.format(getString(R.string.share_web), url));
        map.put("title", title);
        map.put("url", url);
        map.put("imagePath", imageUrl);
        Intent intent = new Intent();
        intent.setClass(this, ShareActivity.class);
        intent.putExtra("showWarnBtn", false);
        intent.putExtra("map", map);
        startActivity(intent);
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    private String getVersion() {
        try {
            PackageManager pm = getApplicationContext().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(getApplicationContext().getPackageName(), 0);
            return pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            return "";
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.destroy();
        }
    }
}